<template>
  <div>
    <section class="header">
      <el-row>
        <el-col justify="center" type="flex">
          <ProductionSteps :active="6" align-center/>
        </el-col>
      </el-row>
    </section>

    <section class="help">
      <HeaderHelpDoc :head-context="headContext"/>
    </section>

    <el-row :gutter="30" class="main-wrap">
      <el-col :span="16" class="main-left">
        <el-row class="scan">
          <el-col>
            <el-card>
              <span>请扫描SN条码: </span>
              <el-input
                v-model="scanBarcode"
                v-loading="loadingScan" clearable
                placeholder="点击此处开始扫描" style="width: 400px; "
                @keydown.native.enter="scanOrInputBarcode">
                <div slot="prepend">
                  <ASelect

                    :clearable="false"
                    :label-attr-name="'Name'" :options="areaList" :val-attr-name="'ProductCombineAreaId'"
                    :value.sync="areaId"
                    placeholder="请选择分区"
                    style="width: 140px;" @change="handleChangeArea"></ASelect>
                </div>
                <el-button slot="append" icon="el-icon-search" type="primary"></el-button>
              </el-input>

              <!--              <span style="padding-left: 30px">下一道工序:</span>-->
              <!--              <span style="padding: 15px">-->
              <!--                <a-button @click="$router.push({name:'productCover'})">产品装封面</a-button>-->
              <!--              </span>-->

            </el-card>
          </el-col>

          <!--          <el-col class="condition-filter">-->
          <!--            <el-row :gutter="30">-->
          <!--&lt;!&ndash;              <el-col :span="7">&ndash;&gt;-->
          <!--&lt;!&ndash;                <line-select :value.sync="selectedLineBody" style="width: 100%;"></line-select>&ndash;&gt;-->
          <!--&lt;!&ndash;              </el-col>&ndash;&gt;-->
          <!--         -->
          <!--              &lt;!&ndash;              <el-col>&ndash;&gt;-->
          <!--              &lt;!&ndash;                <el-button @click="clearGridList">清空全部格子</el-button>&ndash;&gt;-->
          <!--              &lt;!&ndash;              </el-col>&ndash;&gt;-->
          <!--            </el-row>-->
          <!--          </el-col>-->

        </el-row>
      </el-col>
      <!--提示 -->
      <el-col v-show="isShowTip" :span="8" class="main-right">
        <el-card class="box-card">
          <div slot="header">
            <span>提示</span>
          </div>
          <div class="tip-message">{{ SpeechContent }}</div>
          <div v-show="isScanCode" class="tip-message-success"><span>A001</span>号齐套</div>
          <!--          <button @click="playVoice">播放语音</button>-->
          <div v-show="isScanCode">
            <div>产品编码：</div>
            <div>客户作品：</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!--工位 -->
    <!--    <el-row style="padding: 0 10px 0 10px;">-->
    <!--      <el-col>-->
    <!--        <el-row>-->
    <!--          <el-col>-->
    <!--            <el-collapse v-model="activeNames" style="border: 1px solid #e6ebf5">-->
    <!--              <el-collapse-item name="1">-->
    <!--                <template slot="title">-->
    <!--                  <h3 style="text-indent: 1em">工位信息展示</h3>-->
    <!--                </template>-->
    <!--                <el-row class="row-bg" justify="center" type="flex">-->
    <!--                  <el-col :span="5">工位名称：</el-col>-->
    <!--                  <el-col :span="5">工位线体：</el-col>-->
    <!--                  <el-col :span="5">所属车间：</el-col>-->
    <!--                  <el-col :span="5">操作员：</el-col>-->
    <!--                </el-row>-->
    <!--              </el-collapse-item>-->
    <!--            </el-collapse>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <!-- cell list -->
    <!--    <transition-group-->
    <!--      appear-->
    <!--      name="list-complete" style=" flex-wrap: wrap"-->
    <!--      tag="ElRow" type="flex">-->
    <el-row style=" flex-wrap: wrap" type="flex">

      <el-col v-for="(cell,index) in cellList"
              :key="cell.ProductCombineGridId"
              class="list-complete-item"
              style="cursor: pointer;width: 195px;margin:12px;"
              @click.native="handleGrid(index,cell)">

        <!--        <div class="grid-card">-->
        <!-- #909399  #409EFF                     style="background: #F56C6C"
         -->
        <el-card :class="cell.OrderProduct ? 'productIsShowCard' : 'productShowCard'"
                 :style="getCellStyle(cell)"
                 body-style="height: 85px;"
                 class="cell-grid"
                 shadow="hover"
                 style="position: relative">

          <!--     `CELL  -  ${cell.Name}`      -->
          <el-tag
            effect="plain" size="mini" type="info">{{ `CELL  -  A${index + 1}` }}
          </el-tag>
          <div v-if="cell.OrderProduct" style="color: #ffffff;margin-top: 5px;">
            SN：{{ cell.OrderProduct.OrderProductCode }}
          </div>

          <!--            <transition name="el-zoom-in-center">-->
          <el-popconfirm
            v-if="cell.OrderProduct"
            :key="Math.random()"
            cancel-button-text='喝醉了'
            confirm-button-text='当然'
            icon="el-icon-info"
            icon-color="red"
            title="确定要清空当前格子吗？"
            @confirm="()=>clearGrid(cell)"
          >
            <el-button
              v-if="cell.OrderProduct"
              slot="reference"
              class="delete" icon="el-icon-delete"
              plain
              size="mini"
              style="position:absolute;right: 4px;top: 4px;" type="info" @click.stop="log('cell.OrderProduct')">
            </el-button>
          </el-popconfirm>
        </el-card>
      </el-col>

    </el-row>

    <!--    </transition-group>-->

    <el-dialog :visible.sync="gridVisibleSync" title="格子详情" width="1000px">
      <el-tag v-if="this.cellList[openIdx] && this.cellList[openIdx].OrderProduct">
        {{ `商户名 : ${this.cellList[openIdx].OrderProduct.CtmName}` }}
      </el-tag>
      <el-row>
        <AzureDynamicTable :column-des-objs="detailColumnObjs" :data="productCombineGridDetailVos">
          <template slot="InGrid" slot-scope="{scope:{row}}">
            <el-switch :value="row.InGrid" disabled/>
          </template>
          <template slot="NeedScan" slot-scope="{scope:{row}}">
            <el-switch :value="!row.NeedScan" disabled/>
          </template>
        </AzureDynamicTable>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import ProductionSteps from '@/views/productManagement/aComponents/ProductionSteps'
import HeaderHelpDoc from '@/components/ATheFridayClub/HeaderHelpDoc'
import AButton from '@/components/ATheFridayClub/AButton'
import LineSelect from '@/components/ATheFridayClub/businessRelation/LineSelect'
import WorkSitInfo from '@/components/ATheFridayClub/businessRelation/WorkSitInfo'
import ASelect from '@/components/ATheFridayClub/ASelect'
import {clearGrid, GetAllGridArea, GetGridArea, ScanCode} from '@/api/productMerge'
import {ERR_OK} from '@/utils/commons'
import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'

// const synth = window.speechSynthesis
// const msg = new SpeechSynthesisUtterance()
export default {
  name: 'productMerge',
  components: {AzureDynamicTable, ProductionSteps, HeaderHelpDoc, AButton, LineSelect, WorkSitInfo, ASelect},
  data() {
    return {
      headContext: '扫描产品组件，进入指定格子，齐套后进行合册。',
      activeNames: ['1'],
      cellList: [], //格子数据
      gridList: [],
      areaList: [], //分区数据
      scanBarcode: '', //  用户扫描或输入的条形码
      loadingScan: false,
      selectedLineBody: '', //线体使用,用户选择的线体
      areaId: '',
      seen: false,
      current: 0,
      gridVisibleSync: false, //格子默认显示
      openIdx: -1, //格子默认显示
      isScanCode: false,  //是否齐套提示
      isShowTip: true,  //默认显示提示
      SpeechContent: '', //语音播报内容
      productCombineGridDetailVos: [],
      detailColumnObjs: [
        {label: '产品编码', key: 'OrderProductPartCode', tag: true},
        {label: '产品名称', key: 'OrderProductPartName', tag: true},
        {label: '是否在格子中', key: 'InGrid',},
        {label: '是否为特殊组件', key: 'NeedScan',},
      ],

      lastScanData: {},

      scan_status: 1,
      prev_scan_res: null,
    }
  },
  async created() {
    // this.getGridArea()

    await this.getAllGridArea()

  },
  methods: {
    log(str) {
      console.log(str)
    },
    getCellStyle({OrderProduct}) {

      return {
        background: OrderProduct ? '#409EFF' : '#ffffff'
      }
    },

    async clearGrid({ProductCombineGridId, Name}) {
      try {
        await clearGrid({inGridID: ProductCombineGridId})
        this.$message.success(`删除cell [${Name}] 成功!`)
        await this.getGridArea()
      } catch (e) {
        console.log(e)
      }
    },
    /*
    * 获取当前登录岗位的分区信息
    * */
    async getAllGridArea() {
      const {Result, Code} = await GetAllGridArea({})

      if (Code === ERR_OK) {
        this.areaList = Result
      }
    },
    /*
    * 获取选择的分区内的详情
    * */
    async getGridArea() {
      const areaId = this.areaId

      const {Result, Code} = await GetGridArea({areaId})

      //  mock
      // const {Result, Code} = {
      //   Result: {
      //     ProductCombineGridVos: new Array(400).fill({}),
      //   },
      //   Code: ERR_OK
      // }

      if (Code === ERR_OK) {
        this.cellList = Result.ProductCombineGridVos
      }
    },
    // 选择分区
    async handleChangeArea() {
      await this.getGridArea()
    },

    //  在参数中注入
    _scan_barcode(scope, evt) {
      const {target: {value: new_code}} = evt;

      const {prev_scan_res, getData} = scope;

      const FAR_SCAN = 1;
      const NORMAL_SCAN = 2;

      this.scan_status = FAR_SCAN

      const get_scan_status = () => {
        if (!prev_scan_res) {
          return NORMAL_SCAN
        }
        const needScanList = prev_scan_res.filter(v => v.NeedScan);
        const inGridList = needScanList.filter(v => v.InGrid);
        return needScanList.length === inGridList.length
      }

      switch (get_scan_status()) {
        case FAR_SCAN:
          console.log('FAR_SCAN')
          break
        case NORMAL_SCAN:
          console.log('NORMAL_SCAN')
          break
      }

      //  传入的参数处理不同

      //  返回时的提示处理也不同

    },

    //用户使用扫描枪 或者 手动输入
    async scanOrInputBarcode({target}) {
      const {value: code} = target;

      const getLatestScanList = () => {
        return (this?.lastScanData?.ProductCombineGridDetailVos ?? [])
      }

      //  不需要扫描的全部齐全了返回true
      //  在没有皮册时也会返回true
      const isAllReadyCell = () => {
        const needScanList = getLatestScanList().filter(v => v.NeedScan);
        const inGridList = needScanList.filter(v => v.InGrid);
        return needScanList.length === inGridList.length
      }

      if (!this.areaId) {
        this.$message.warning('请先选择分区')
        this.$speakText('请先选择分区')
        return
      }

      const params = {
        AreaId: this.areaId,
        Code: code,
        OtherCode: Array.of(),
      }

      //  参数处理
      //  当用户重复扫描时要把上一次的一些 code 传到OtherCode 来作为参数
      const hasExistCode = getLatestScanList().some(v => v.OrderProductPartCode === code)

      if (hasExistCode && isAllReadyCell()) {
        Object.assign(params, {
          OtherCode: getLatestScanList().filter(v => !v.NeedScan).map(v => v.OrderProductPartCode)
        })
      }

      try {

        const {Code, Message, Result} = await ScanCode(params)

        if (Code === ERR_OK) {
          const {SpeechContent, ProductCombineGridDetailVos, ClearGrid} = Result;
          //  如果有某一个不需要扫描的特殊组件 就查看是否到齐,

          //  全部到齐的情况
          if (isAllReadyCell()) {
            //  皮册到齐的情况

            //  NeedScan 皮册组件会返回 false,不需要扫描
            //  InGrid  是否在格子中,该组件是否已经被扫描

            if (ProductCombineGridDetailVos.some(v => !v.NeedScan)) {
              this.$notify({
                title: '当前产品缺少以下特殊组件',
                message: `{ ${getLatestScanList().filter(v => !v.NeedScan)
                  .map(({OrderProductPartName}) => `[ ${OrderProductPartName ?? '未知'} ]`)
                  .join(',')} }  请在以上组件全部获取齐全后再次扫描最后一次扫描的组件号以完成合册.`,
                type: 'info',
                duration: 8000
              })
              // this.$speakText('皮册产品已齐套')
            }

            // else {
            //   this.$speakText('产品已齐套')
            // }

            this.lastScanData = {}    //  清空旧数据 ??
          } else {
            // this.$speakText('产品入格成功')
            this.lastScanData = Result  //  在这里已经没有利用价值了
          }

          this.SpeechContent = SpeechContent
          Message && this.$message.info(Message)

          //  服务端提示语音
          this.$speakText(SpeechContent)

          //  只有两种状态 修改格子信息和删除格子信息
          //  删除的话返回一个空的对象,只有格子信息
          //  插入的话里面就多了一个格子的信息
          // if (ClearGrid) {
          this.cellList = this.cellList.map((v) => {
            const {ProductCombineGridId} = v
            return Result.ProductCombineGridId === ProductCombineGridId ? Result : v
          })
          // this.cellList = ProductCombineGridDetailVos.filter(v => v.OrderProductPartCode === code);
          // } else {
          //   // await this.getGridArea()
          //   //  update by ProductCombineGridId
          //   this.cellList = this.cellList.map((v) => {
          //     const {ProductCombineGridId} = v
          //     return Result.ProductCombineGridId === ProductCombineGridId ? Result : v
          //   })
          // }

        }
      } catch (e) {
        console.log(e)
        this.$speakText('扫描错误' + e.message)
      } finally {
        target.value = ''
      }
    },

    handleGrid(index, {OrderProduct}) {
      if (!OrderProduct) {
        return
      }
      this.gridVisibleSync = true
      this.openIdx = index
      this.productCombineGridDetailVos = this.cellList[index].ProductCombineGridDetailVos
      console.log(this.productCombineGridDetailVos, 216)
    },


  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/index.scss";

.text-break {
  cursor: pointer;
  @include noWrap()
}

.header {
  padding: 10px 0;
}

.help {
  padding: 10px;
}

.main-wrap {
  padding: 10px;
  font-size: $mainSize;

  .main-left {
    min-width: 840px;

    .scan {
      .operator-area {
        padding: 15px 10px;
        border: 1px solid $borderColor;
        border-radius: 3px;
      }

      .condition-filter {
        padding: 30px 0;
      }
    }

  }

  .main-right {
    min-width: 350px;

    .tip-message {
      font-size: 36px;
      font-weight: bolder;
      text-align: center;
      letter-spacing: 1px;

      span {
        color: #E6A23C;
      }
    }

    .tip-message-success {
      font-size: 36px;
      font-weight: bolder;
      text-align: center;
      letter-spacing: 1px;

      span {
        color: #67C23A;
      }
    }
  }
}

.delete {
  opacity: 0;
  transition: all .3s linear;
}

.cell-grid {
  &:hover {
    .delete {
      opacity: 1;
    }
  }
}

</style>
<style>

/deep/ .productIsShowCard {
  background-color: #F56C6C;
  color: #fff;
}

.el-input-group__prepend {
  background: #ffffff;
}


</style>
